let url = "https://www.yuque.com/yashujs/bfug6u";

// https://www.yuque.com/yashujs/bfug6u/fr8o07

// /yashujs/bfug6u/fr8o07

var request = require("request");
const fs = require("fs");

var http = (uri) => {
  return new Promise((resolve, reject) => {
    request(
      {
        uri: uri,
        method: "GET",
      },
      (err, response, body) => {
        if (err) {
          console.log(err);
        }
        resolve(body);
      }
    );
  });
};
function 提取windowAppData(html) {
  let regStr = `\\(function\\(\\) {\\s+window.appData = JSON.parse\\(decodeURIComponent\\("[\\s\\S]+?"\\)\\);\\s+}\\)\\(\\);`;

  let reg = new RegExp(regStr, "m");
  console.log(reg);
  let result = html.match(reg);
  if (result && result[0]) {
    return result[0];
  }
}
function 去掉多余部分(filePath) {
  let r = fs.readFileSync(filePath, "utf8");
  return r.replace("(function() {", "").replace("})();", "").replace("window.appData", "appData");
}

function appData写入文件(data) {
  let filePath = "appData文件.txt";
  fs.writeFileSync(filePath, data, "utf8");
  return filePath;
}

function getData() {
  return new Promise((resolve, reject) => {
    // 定义目标网址
    var target = url;
    // 使用request.js库发送get请求
    http(target).then((html) => {
      // console.log(html)
      let appData = 提取windowAppData(html);
      if (!appData) {
        console.log("未匹配到数据");
        return false;
      }
      let filePath = appData写入文件(appData);
      let appDataStr = 去掉多余部分(filePath);
      eval(appDataStr);
      let toc = appData.book.toc;
      console.log(toc);
      resolve(toc);
    });
  });
}

module.exports = getData;
